$(function(){
  $("#farticulo").autocomplete({
    source: base_url+'panel/infografia/ajax_get_articulos',
    minLength: 1,
    selectFirst: true,
    select: function( event, ui ) {
      $("#fid").val(ui.item.id);
      $("#fnombre_a").val(ui.item.value);
    }
  });

  $("#farticulo").on("keydown", function(event) {
    if(event.which === 8 || event === 46) {
      $("#fid").val('');
      $("#fnombre_a").val('');
      $(this).val('');
    }
  });

  $('#farticulo').on('keydown', function(event) {
    if (event.which === 13) {
      return false;
    }
  });

  upload_multiple.init({form: '#formImgs', inputfile: '#fimagenes', bar: '.bar', percent: '.percent'});
});



//
var upload_multiple = (function ($) {

  var config = {},
      module = {},
      parent,
      uniqid = 0;

  // Inicializa el plugin
  function initialize (conf) {
    if (typeof conf === "object") {
      setConfig(conf);
    }
    inputFileOnChange();
  }

  // Asignamos la configuracion
  function setConfig (conf) {
    if (typeof conf === "object") {
      config = conf;
      console.log(conf);
    } else {
      console.log("El parametro debe ser tipo Object i.e. {form: '#formImgs', inputfile: '#fimagenes', bar: '.bar', percent: '.percent'}");
    }
  }

  // Asigna el evento onChange al o los input-file especificados en el config
  function inputFileOnChange () {
    $(config.inputfile).on('change', $('body'), function(event) {
      parent = $(this).parent().parent();
      submitForm();
    });
  }

  function showInputFile () {
    parent.children('#progress-bar, .percent').remove();
    $('#uniform-fimagenes > .filename').html("No file selected");
    $('#fimagenes').val("");
    parent.children().css({"display":"block"}); // Muestra el input-file original
  }

  function deleteThumb (obj) {

    var parent = $(obj).parent().parent().parent(),
        big   = parent.children('.thumbnail').children('#fpath').val(),
        thumb = parent.children('.thumbnail').children('#fthumb').val(),
        ida   = parent.children('.thumbnail').children('#fid_a').val();

    $.post(base_url+'panel/infografia/ajax_delete', {"big": big, "thumb": thumb}, function(resp) {
      console.log(resp);
      if (resp.status === true) {
        parent.animate({
          opacity: 0.4
        }, 1000, function () {
          parent.remove();
        });
      }
    }, "json");
  }

  function submitForm () {
    var html_progress_bar = '<div class="progress progress-striped active" style="margin-bottom: 9px; width: 30%;" id="progress-bar"><div class="bar" style="width: 0%"></div></div><span class="help-block percent">0%</span>';
    parent.children().css({"display":"none"}); // Oculta el input-file original
    $(html_progress_bar).appendTo(parent); // Agrega el html del progress-bar
    ajaxForm();
    $(config.form).submit(); // Realiza el envio del formulario
  }

  // Inicializa el plugin ajaxForm para asignar el evento al formulario
  function ajaxForm () {
    var bar = $(config.bar),
    percent = $(config.percent);
    // var status = $(config.status);

    $(config.form).ajaxForm({
      beforeSend: function () {
          // status.empty();
          var percentVal = '0%';
          bar.width(percentVal)
          percent.html(percentVal);
      },
      uploadProgress: function (event, position, total, percentComplete) {
          var percentVal = percentComplete + '%';
          bar.width(percentVal)
          percent.html(percentVal);
          // console.log(percentVal, position, total);
      },
      success: function (response, statusText, xhr, wrap) {
          console.log(response);
         if (response.status === 1) {
            createThumb(response.resp);
            showInputFile();
         }
         // else {
         //    var parent = $('#uniform-'+response.element).parent();
         //    parent.children("#progress-bar, .percent").remove();
         //    $('#uniform-'+response.element).css({"display":"block"});

         //    noty({"text":response.resp, "layout":"topRight", "type":"error"});
         //  }
      },
      dataType: 'json'
    });

    function createThumb (arrayPaths) {
      var thumbs = $('#thumbs'),
          htmlThumbs = '',
          i = arrayPaths.length,
          path,
          style;

      while (i--) {

        path = arrayPaths[i].path.split('application/');
        thumb = base_url + arrayPaths[i].thumb;

        style = '';
        // if (uniqid % 4 === 0) {
        //   style = 'style="margin-left:0px;"';
        // }

        htmlThumbs +='<li class="span3" id="thumb" '+style+'>' +
                      '<div class="thumbnail" style="z-index: 0;">' +
                        '<img src="'+thumb+'" alt="" width="260" height="180" style="width: 260px; height: 180px; z-index: 0;">' +
                        '<label>Titulo</label><input type="text" name="ftitulo[]" value="">' +
                        '<label>Tags</label><input type="text" name="ftags[]" value="">' +
                        '<input type="hidden" name="fpath[]" id="fpath" value="application/'+path[1]+'">' +
                        '<input type="hidden" name="fthumb[]" id="fthumb" value="'+arrayPaths[i].thumb+'">' +
                        '<p><button type="button" class="btn btn-mini btn-danger" id="deleteThumb" onclick="upload_multiple.deleteThumb(this)"><i class="icon-trash"></i></button></p>' +
                      '</div>' +
                    '</li>';

        // uniqid = uniqid + 1;
      }

      $(htmlThumbs).appendTo(thumbs);
    }
  }

  module.init         = initialize;
  module.setConfig    = setConfig;
  module.deleteThumb = deleteThumb;

  return module;

})(jQuery);